﻿package com.edward.action;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.struts2.ServletActionContext;
import org.springframework.security.annotation.Secured;

import com.edward.JsonDateProcessor;
import com.edward.PagerModel;
import com.edward.model.Cargo;
import com.edward.model.InvoiceItem;
import com.edward.model.InvoiceList;
import com.edward.model.SL_Cargo;
import com.edward.model.ShoppingList;
import com.edward.service.CargoManager;
import com.edward.service.InvoiceItemManager;
import com.edward.service.SL_CargoManager;
import com.edward.service.ShoppingListManager;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ShoppingListAction extends ActionSupport {

	private static final long serialVersionUID = -214721038137716643L;

	private ShoppingListManager shoppingListManager;
	
	private InvoiceItemManager invoiceItemManager;
	
	private SL_CargoManager sl_CargoManager;

	private CargoManager cargoManager;
	
	private SL_Cargo sl_Cargo;
	
	private Cargo cargo;
	
	private int limit;
	
	private int start;
	
	private String query;
	
	private boolean flag = false;
	
	
	private ShoppingList shoppingList;
	
	private int id;
	
	private List <SL_Cargo> goods;
	
	public List<SL_Cargo> getGoods() {
		return goods;
	}


	public void setGoods(List<SL_Cargo> goods) {
		this.goods = goods;
	}


	public int getId() {
		return id;
	}


	public void setId(int id) {
		this.id = id;
	}


	public ShoppingList getShoppingList() {
		return shoppingList;
	}


	public void setShoppingList(ShoppingList shoppingList) {
		this.shoppingList = shoppingList;
	}


	public void setShoppingListManager(ShoppingListManager shoppingListManager) {
		this.shoppingListManager = shoppingListManager;
	}

	

	public void setInvoiceItemManager(InvoiceItemManager invoiceItemManager) {
		this.invoiceItemManager = invoiceItemManager;
	}


	public int getLimit() {
		return limit;
	}


	public void setLimit(int limit) {
		this.limit = limit;
	}


	public int getStart() {
		return start;
	}


	public void setStart(int start) {
		this.start = start;
	}
	
	public String getQuery() {
		return query;
	}


	public void setQuery(String query) {
		this.query = query;
	}
	
	
	public boolean isFlag() {
		return flag;
	}


	public void setFlag(boolean flag) {
		this.flag = flag;
	}


	public SL_Cargo getSl_Cargo() {
		return sl_Cargo;
	}


	public void setSl_Cargo(SL_Cargo slCargo) {
		sl_Cargo = slCargo;
	}


	public Cargo getCargo() {
		return cargo;
	}


	public void setCargo(Cargo cargo) {
		this.cargo = cargo;
	}


	public void setSl_CargoManager(SL_CargoManager slCargoManager) {
		sl_CargoManager = slCargoManager;
	}


	public void setCargoManager(CargoManager cargoManager) {
		this.cargoManager = cargoManager;
	}


	//添加shoppinglist 的表头
	@Secured("ROLE_ORDER_ADD")
	public String add() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		shoppingList.setState("新建");
		
		//判断如果code = 0 说明直接添加采购单 ，否则是从订单转移过来的
		
		if(shoppingList.getCode().equals("0")){
			shoppingList.setInvoiceID(0);
		}else{
		InvoiceList  i = shoppingListManager.getInvoice(shoppingList.getCode());
		shoppingList.setInvoiceID(i.getId());
		}
		shoppingList.setListNum(shoppingListManager.listNum());
		shoppingListManager.addShoppingList(shoppingList);
		int total  = shoppingListManager.listShoppingList(shoppingList.getInvoiceID()).size();
		response.getWriter().print("{success : true , msg : '添加成功!',shoppingList_id:"+ shoppingList.getId()+",total: "+total +",id: "+shoppingList.getInvoiceID() +"}");
		return null;
	}
	
	@Secured("ROLE_ORDER_UPDATE")
	public String update() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		ShoppingList s = shoppingListManager.getShoppingList(shoppingList.getId());
		shoppingList.setState(s.getState());
		shoppingList.setTotal(s.getTotal());
		shoppingList.setGoods(s.getGoods());
		shoppingListManager.updateShoppingList(shoppingList);
		response.getWriter().print("{success : true , msg : '修改成功!'}");
		return null;
	}
	
	@Secured("ROLE_ORDER_UPDATE")
	public String delete() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		ShoppingList s = shoppingListManager.getShoppingList(shoppingList.getId());
		if(s.getGoods().size() != 0){
			response.getWriter().print("{success:false, msg : '删除失败，存在采购货物列表，请先删除采购货物!'}");
		}else{
			shoppingListManager.deleteShoppingList(s.getId());
			response.getWriter().print("{success : true , msg : '删除成功!',id : "+ s.getInvoiceID() + "}");
		}
		return null;
	}
	
	//获取采购单 显示 的 分页信息
	public String getList() throws Exception {

		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
	    JsonConfig cfg = new JsonConfig();
		cfg.registerJsonValueProcessor(java.util.Date.class, new JsonDateProcessor());
		cfg.registerJsonValueProcessor(java.sql.Date.class, new JsonDateProcessor());
		PagerModel pager;
		pager = shoppingListManager.pagerSL(start,limit,id);
		JSONObject jsonObject = JSONObject.fromObject(pager,cfg);
		String jsonStr = jsonObject.toString();
		response.getWriter().print(jsonStr);
		return null;
	}
	
	
	//获取采购单 显示 的 分页信息
	public String getALLList() throws Exception {

		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
	    JsonConfig cfg = new JsonConfig();
		cfg.registerJsonValueProcessor(java.util.Date.class, new JsonDateProcessor());
		cfg.registerJsonValueProcessor(java.sql.Date.class, new JsonDateProcessor());
		PagerModel pager;
		if(!flag){
		pager = shoppingListManager.pagerSL(start,limit);
		}else{
		pager = shoppingListManager.pagerSL(start,limit,shoppingList);	
		}
		JSONObject jsonObject = JSONObject.fromObject(pager,cfg);
		String jsonStr = jsonObject.toString();
		response.getWriter().print(jsonStr);
		return null;
	}
	
	
	//添加shoppingList 的 货物明细
	@Secured("ROLE_ORDER_ADD")
	public String addSLCargo() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		ShoppingList s = shoppingListManager.getShoppingList(shoppingList.getId());
		
	//判断采购单的状态，如果不是新建则不允许添加
		if(!s.getState().equals("新建")){
			response.getWriter().print("{failure:true, msg : '添加失败，只有处于新建状态的采购单能添加采购项!'}");
			return null;
		}
		
		//找到对应的订单，跟新他的采购数量
		if(s.getInvoiceID() != 0){
			InvoiceList i = shoppingListManager.getInvoice(s.getInvoiceID());
			List <InvoiceItem> list = i.getItems();
			for (InvoiceItem item : list){
				if(item.getDog().equals(cargo.getName())){
					if((item.getQty()-item.getCount())<sl_Cargo.getAmount()){
						response.getWriter().print("{failure:true, msg : '添加失败，采购数量大于订单数量!'}");
						return null;
					}
					item.setCount(item.getCount() + sl_Cargo.getAmount());
					invoiceItemManager.updateInvoiceItem(item);
				}
			}
		}
		
		
		if(cargo.getId() == 0){
			cargo.setPrice(sl_Cargo.getPrice());
	//为以后删除 作标志，表明由采购单添加
			cargo.setSign("sl");
			cargoManager.addCargo(cargo);
		}else{
		    Cargo c = cargoManager.getCargo(cargo.getId());
		    cargo.setSign(c.getSign());
		    cargo.setLocation(c.getLocation());
		    cargo.setPlace(c.getPlace());
		    if(sl_Cargo.getPrice()!= 0){
		    	cargo.setPrice(sl_Cargo.getPrice());
		    }else{
		    	cargo.setPrice(c.getPrice());
		    }
		    cargo.setCount(c.getCount());
		    
		    cargoManager.updateCargo(cargo);
		}
		sl_Cargo.setCargo(cargo);
		sl_Cargo.setSum(sl_Cargo.getPrice() * sl_Cargo.getAmount());
		sl_Cargo.setState("未完成");
		sl_CargoManager.addSL_Cargo(sl_Cargo);
		s.setTotal(s.getTotal() + sl_Cargo.getSum());
		s.getGoods().add(sl_Cargo);
		shoppingListManager.updateShoppingList(s);
		response.getWriter().print("{success : true , msg : '添加成功!'}");
		return null;
	}
	

	
	//更新SLcargo
	@Secured("ROLE_ORDER_UPDATE")
	public String updateSLCargo() throws Exception {

		ActionContext ctx = ActionContext.getContext();        
		  HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		SL_Cargo sl = sl_CargoManager.getSL_Cargo(sl_Cargo.getId());
		ShoppingList s = shoppingListManager.getShoppingList(shoppingList.getId());
		
		//判断采购单的状态，如果不是新建则不允许更新
	
		if(!s.getState().equals("新建")){
			response.getWriter().print("{failure:true, msg : '修改 失败，只有处于新建状态的采购单能修改采购项!'}");
			return null;
		}
		
		//找到对应的订单，更新他的采购数量
		if(s.getInvoiceID() != 0){
			InvoiceList i = shoppingListManager.getInvoice(s.getInvoiceID());
			List <InvoiceItem> list = i.getItems();
			for (InvoiceItem item : list){
				if(item.getDog().equals(cargo.getName())){
					int x =  sl_Cargo.getAmount()- sl.getAmount();
					if((item.getQty()-item.getCount())< x){
						response.getWriter().print("{failure:true, msg : '修改失败，采购数量大于订单数量!'}");
						return null;
					}
					item.setCount(item.getCount() + x);
					invoiceItemManager.updateInvoiceItem(item);
				}
			}
		}
		
		
		s.setTotal(s.getTotal() + sl_Cargo.getPrice() * sl_Cargo.getAmount() - sl.getAmount() * sl.getPrice());
		shoppingListManager.updateShoppingList(s);
		//由于变更的cargo没有Id ,先从数据库中获取其ID 再一同更新
		Cargo c =sl.getCargo();
		cargo.setSign(c.getSign());
		cargo.setId(c.getId());
		cargo.setLocation(c.getLocation());
		cargo.setPlace(c.getPlace());
		if(c.getSign().equals("sl")){
			cargo.setPrice(sl_Cargo.getPrice());
		}else{
			cargo.setPrice(c.getPrice());
		}
		cargo.setCount(c.getCount());
		sl_Cargo.setCargo(cargo);
		cargoManager.updateCargo(cargo);
		sl_Cargo.setSum(sl_Cargo.getPrice() * sl_Cargo.getAmount());
		sl_Cargo.setState(sl.getState());
		sl_CargoManager.updateSL_Cargo(sl_Cargo);
		response.getWriter().print("{success : true , msg : '修改成功!'}");
		return null;
	}
	
	@Secured("ROLE_ORDER_UPDATE")
	public String deleteSLCargo() throws Exception {

		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		ShoppingList s = shoppingListManager.getShoppingList(shoppingList.getId());
		
		//判断采购单的状态，如果不是新建则不允许删除
		if(!s.getState().equals("新建")){
			response.getWriter().print("{success:false, msg : '添加失败，只有处于新建状态的采购单能删除采购项!'}");
			return null;
		}
		SL_Cargo sl = sl_CargoManager.getSL_Cargo(sl_Cargo.getId());
		//找到对应的订单，跟新他的采购数量
		
		if(s.getInvoiceID() != 0){
			InvoiceList i = shoppingListManager.getInvoice(s.getInvoiceID());
			List <InvoiceItem> list = i.getItems();
			for (InvoiceItem item : list){
				if(item.getDog().equals(sl.getCargo().getName())){
					item.setCount(item.getCount() - sl.getAmount());
					invoiceItemManager.updateInvoiceItem(item);
				}
			}
		}
		
		
		s.setTotal(s.getTotal() - sl.getPrice() * sl.getAmount());
		shoppingListManager.updateShoppingList(s);
		if(sl_CargoManager.check(sl.getCargo().getId())){
			sl_CargoManager.deleteSL_Cargo(sl_Cargo.getId());
			cargoManager.deleteCargo(sl.getCargo().getId());
		}else{
			sl_CargoManager.deleteSL_Cargo(sl_Cargo.getId());
		}
		response.getWriter().print("{success : true , msg : '删除成功!'}");
		return null;
	}
	
	//获取grid 显示 的 分页信息
	public String getSLCargo() throws Exception {

		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
	    JsonConfig cfg = new JsonConfig();
		cfg.registerJsonValueProcessor(java.util.Date.class, new JsonDateProcessor());
		cfg.registerJsonValueProcessor(java.sql.Date.class, new JsonDateProcessor());
		PagerModel pager;
		if(query!= null){
			pager = sl_CargoManager.pagerSLCargo(start, limit,shoppingListManager.getShoppingList(query).getId());
		}else{
		pager = sl_CargoManager.pagerSLCargo(start, limit,shoppingList.getId());
		}
		JSONObject jsonObject = JSONObject.fromObject(pager,cfg);
		String jsonStr = jsonObject.toString();
		response.getWriter().print(jsonStr);
		return null;
	}


	
	@SuppressWarnings("unchecked")
	public String getCargosByCode() throws Exception{
		
		ActionContext ctx = ActionContext.getContext();        
		  HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		List list = cargoManager.getCodes(query);
		  String json="";
		  JSONArray jsonArray;
		  jsonArray = JSONArray.fromObject(list);
		  json = jsonArray.toString();
		json  = "{\"codes\":"  + json + "}";
		response.getWriter().print(json);
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public String getCargosByname() throws Exception {
		
		
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		List list = cargoManager.getNames(query);
		  String json="";
		  JSONArray jsonArray;
		  jsonArray = JSONArray.fromObject(list);
		  json = jsonArray.toString();
		json  = "{\"names\":"  + json + "}";
		response.getWriter().print(json);
		return null;
	}
	
	public String apply() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		ShoppingList s = shoppingListManager.getShoppingList(id);
		if(!s.getState().equals("新建")){
			response.getWriter().print("{success:false, msg : '只用在新建状态的采购单才能提交申请!'}");
			return null;
		}
		
		s.setState("采购申请");
		shoppingListManager.updateShoppingList(s);
		response.getWriter().print("{success : true , msg : '成功提交申请!'}");
		return null;
	}
	
	
	public String action() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		ShoppingList s = shoppingListManager.getShoppingList(id);
		if(!s.getState().equals("确认申请")){
			response.getWriter().print("{success:false, msg : '只用在确认申请态的采购单才能进行采购!'}");
			return null;
		}
		
		s.setState("正在采购");
		shoppingListManager.updateShoppingList(s);
		response.getWriter().print("{success : true , msg : '成功提交申请!'}");
		return null;
	}
	
	public String confirm() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		ShoppingList s = shoppingListManager.getShoppingList(id);
		if(!s.getState().equals("采购申请")){
			response.getWriter().print("{success:false, msg : '只用在采购申请状态的采购单才能确认申请!'}");
			return null;
		}
		s.setState("确认申请");
		s.setRemark(shoppingList.getRemark());
		shoppingListManager.updateShoppingList(s);
		response.getWriter().print("{success : true , msg : '成功提交申请!'}");
		return null;
	}
	
	public String queryList() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		 JsonConfig cfg = new JsonConfig();
			cfg.registerJsonValueProcessor(java.util.Date.class, new JsonDateProcessor());
			cfg.registerJsonValueProcessor(java.sql.Date.class, new JsonDateProcessor());
			PagerModel pager;
			pager = shoppingListManager.pagerSL(start,limit,shoppingList);
			JSONObject jsonObject = JSONObject.fromObject(pager,cfg);
			String jsonStr = jsonObject.toString();
			response.getWriter().print(jsonStr);
			response.getWriter().print("{success : true ,jsonStr: "+ jsonStr + "}");
		return null;
	}
	
	@Secured("ROLE_ORDER")
	 public String getListJudge() throws Exception {
			ActionContext ctx = ActionContext.getContext();        
			HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
			response.setContentType("text/html;charset=UTF-8");
				response.getWriter().print("{success : true , msg : '成功!',deny:false}");
		 return null;
	 }

	

	
	
}
